package com.atguigu.gulimall.order.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.annotation.PostConstruct;

/**
 * @author kabuda
 * @create 2022-12-06 11:05
 */
@Configuration
public class RabbitConfig {
    //@Autowired
    private RabbitTemplate rabbitTemplate;


    //代码整合 actuator 后，启动报错，出现rabbitMQ循环依赖的问题
    //1.注释掉 @Autowired和@PostConstruct注解
    //2。自己给容器中放一个RabbitTemplate,参考RabbitAutoConfiguration$RabbitTemplateConfiguration.class
    //3.手动初始化模板方法
    @Primary
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        this.rabbitTemplate = rabbitTemplate;
        rabbitTemplate.setMessageConverter(messageConverter());
        initRabbitTemplate();
        return rabbitTemplate;
    }


    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }



    //@PostConstruct //RabbitConfig对象创建完就会执行
    public void initRabbitTemplate() {
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            /**
             *  无论成功失败都会调用
             * @param correlationData  消息唯一id
             * @param b  消息是否成功收到
             * @param s  失败原因
             */
            @Override
            public void confirm(CorrelationData correlationData, boolean b, String s) {
                System.out.println("correlationData" + correlationData + b + s);
                System.out.println("如果broker收不到，进行处理");
            }
        });

        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            /**
             *  只要没有他偶滴给指定队列，就会调用
             * @param message 投递失败的消息详细信息
             * @param i    回复的状态码
             * @param s    回复的文本内容
             * @param s1    这个消息发送给的交换机
             * @param s2    这个消息用的路由剪
             */
            @Override
            public void returnedMessage(Message message, int i, String s, String s1, String s2) {
                System.out.println(""+message+i+s+s1+s2);
                System.out.println("失败后的处理");
            }
        });


    }


}
